/**  
 * @Title: WaimaiControl.java
 * @Package com.silverbox.sweeporder.controller.waimai
 * @author litao
 * @date 2018年1月2日
 */
package com.silverbox.sweeporder.controller.waimai;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.silverbox.core.util.Utils;
import com.silverbox.sweeporder.controller.waimai.entryvo.*;
import com.silverbox.sweeporder.controller.waimai.outvo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.silverbox.core.result.CoreResponse;
import com.silverbox.core.result.CoreResponse.StatusInfo;
import com.silverbox.core.util.StringUtils;
import com.silverbox.sweeporder.common.Constants;
import com.silverbox.sweeporder.service.waimai.WaimaiOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * ClassName: WaimaiControl
 * 
 * @author litao
 * @date 2018年1月2日
 */
@Controller
@RequestMapping("waimai")
@Api(tags = { "订单接口" })
public class WaimaiController {

	private static Logger logger = LoggerFactory.getLogger(WaimaiController.class);

	@Autowired
	private WaimaiOrderService waimaiOrderService;
	
	@Value("${koubeiUploadUrl}")
	private String koubeiUploadUrl;

	@Value("${uploadOrderFlag}")
	private String uploadOrderFlag;

	@Value("${uploadUrl}")
	private String uploadUrl;

	@RequestMapping(value = "createWaimaiOrder", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "创建订单（在线订单 clientOrderMode 必传）")
	public CoreResponse<SaveWaimaiVO> createWaimaiOrder(HttpSession session, HttpServletRequest request,
			@RequestBody(required=true) CreateWaimaiEntryDto createWaimai) {
		CoreResponse<SaveWaimaiVO> res = new CoreResponse<SaveWaimaiVO>();

		if (createWaimai==null || StringUtils.isEmpty(createWaimai.getBuyerId()) || createWaimai.getStoreId() == null
				|| createWaimai.getIsOut() == null || createWaimai.getClientOrderMode()==null) {
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("下单失败,参数异常");
			return res;
		}
        if(Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue().equals(createWaimai.getClientOrderMode())){
            //在线订单创建
            res = waimaiOrderService.createOnlineOrder(createWaimai);
        } else if(Constants.clientOrderMode.WAIMAI_ORDER_MODE.getValue().equals(createWaimai.getClientOrderMode())){
            //外卖订单
            res = waimaiOrderService.createWaimaiPickingOrder(createWaimai);
        } else{
            //扫码下单订单创建
            res = waimaiOrderService.createWaimaiOrder(createWaimai);
        }
		return res;
	}

	/**
	 *<pre>
	 * 说    明: 命中优惠券，更新订单优惠信息
	 * 涉及版本:
	 * 创 建 者: YangYangjun
	 * 日    期: 2020-04-17 21:38
	 *</pre>
	 **/
    @RequestMapping(value = "promoteOrder", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "选用优惠券，更新订单信息")
    public CoreResponse<Object> promoteOrder(@RequestBody(required=true) PromoteOrderDto promoteOrder) throws Exception{
        CoreResponse<Object> res = new CoreResponse<>();
        if(Utils.isEmpty(promoteOrder.getStoreId())
                || Utils.isEmpty(promoteOrder.getPromoteMemberRule())
                || Utils.isEmpty(promoteOrder.getBuyerId())
                || Constants.PromoteMemberRule.SINGLE_ORDER.getValue().equals(promoteOrder.getPromoteMemberRule()) && Utils.isEmpty(promoteOrder.getOrderNum())){
            res.setStatusInfo(StatusInfo.ERROR_40002);
            res.setSubMsg("操作失败,参数异常");
            return res;
        }
        synchronized (this){
            res = waimaiOrderService.promoteOrder(promoteOrder);
        }
        return res;
    }

    @RequestMapping(value = "getMyOrder",method=RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取进行中订单信息（可调用）")
	public CoreResponse<WaimaiVO> getMyOrder(OrderQueryDto orderQueryVo) {

		CoreResponse<WaimaiVO> res = new CoreResponse<>();
		if (orderQueryVo.getStoreId() == null || StringUtils.isEmpty(orderQueryVo.getBuyerId())) {
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("参数异常！请检查参数");
			return res;
		}
		res = waimaiOrderService.getMyOrder(orderQueryVo);
		return res;
	}

	@RequestMapping(value = "getHistoryOrder", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取分页查询历史订单信息（可调用）")
	public CoreResponse<HistoryOrderVO> getHistoryOrder(HttpSession session,
			@RequestParam(required = true) String buyerId, @RequestParam(required = true) Integer storeId,
			@RequestParam(required = true) Integer pageCount, @RequestParam(required = false) String createTime,
			@RequestParam(required = false) Integer clientOrderMode) {
	
		CoreResponse<HistoryOrderVO> res = new CoreResponse<HistoryOrderVO>();
		if(StringUtils.isEmpty(buyerId) || storeId==null || pageCount==null){
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("参数异常！请检查参数");
			return res;
		}
		res = waimaiOrderService.getHistoryOrderDetail(storeId, buyerId, pageCount,
				createTime,clientOrderMode);
		return res;
	}
	
	@RequestMapping(value = "cancelMyOrder", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "取消订单（可调用）")
	public CoreResponse<StatusInfo> deleteMyOrder(HttpSession session, HttpServletRequest request,
			@RequestBody(required=true) Map<String,String> orderNum) {
	
		CoreResponse<StatusInfo> res = new CoreResponse<StatusInfo>();
		
		if (orderNum==null || StringUtils.isEmpty(orderNum.get("orderNum"))) {
			res.setStatusInfo(StatusInfo.ERROR_40002);
			return res;
		}
		res = waimaiOrderService.deleteMyOrderAndRes(orderNum.get("orderNum"));
		
		return res;
	}

	@RequestMapping(value = "getGoodsCoupon", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "领取优惠券（可调用）")
	public CoreResponse<StatusInfo> getGoodsCoupon(HttpSession session, @RequestParam(required = true) String buyerId,
			@RequestParam(required = true) String shopId, @RequestParam(required = true) Integer storeId,
			@RequestParam(required = true) String orderNum,@RequestParam(required = false) Integer authMode) {
		CoreResponse<StatusInfo> res = new CoreResponse<StatusInfo>();
		if (StringUtils.isEmpty(shopId) || StringUtils.isEmpty(buyerId) || StringUtils.isEmpty(orderNum)
				|| storeId == null) {
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setSubMsg("参数异常，请检查参数");
			return res;
		}
		 res = waimaiOrderService.getGoodsCouponV2(buyerId,shopId,storeId,orderNum,authMode);
		
		return res;
	}

	@RequestMapping(value = "getKoubeiDiscountInfo", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "优惠前置（可调用）")
	public CoreResponse<KoubeiDiscountInfoVO> getKoubeiDiscountInfo(HttpSession session,
			@RequestBody(required = true) KoubeiDiscountEntryVO koubeiDiscount) {
		
		CoreResponse<KoubeiDiscountInfoVO> res = new CoreResponse<KoubeiDiscountInfoVO> ();
		
		if (koubeiDiscount == null || StringUtils.isEmpty(koubeiDiscount.getBuyerId())
				|| koubeiDiscount.getStoreId() == null || StringUtils.isEmpty(koubeiDiscount.getOrderNum())) {
			res.setStatusInfo(StatusInfo.ERROR_40002);
			return res;
		}
		res = waimaiOrderService.getKoubeiDiscountInfo(koubeiDiscount);

		return res;
	}

	@RequestMapping(value = "getGoodsAndOrderState", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "购物车页面创建订单时判断是否存在已售罄商品及获取订单状态")
	public CoreResponse<GoodsAndOrderStateVO> getGoodsAndOrderState(@RequestParam(required = true) Integer storeId, @RequestParam(required = true) String buyerId,
			@RequestParam(required = false) String tableName,@RequestParam(required=false) Integer clientOrderMode) {

		CoreResponse<GoodsAndOrderStateVO> res = new CoreResponse<GoodsAndOrderStateVO>();
		if(storeId==null || StringUtils.isEmpty(buyerId)){
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("参数异常！请检查参数");
			return res;
		}
		res = waimaiOrderService.getGoodsAndOrderState(storeId, buyerId,
				tableName,clientOrderMode);
		return res;
	}
	
	@RequestMapping(value = "deleteHistoryOrder", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "批量删除历史订单")
	public CoreResponse<StatusInfo> deleteHistoryOrder(HttpSession session,
			@RequestBody(required=true) Map<String,Object> orderNums) {

		CoreResponse<StatusInfo> res = new CoreResponse<StatusInfo>();
		
		if (orderNums == null || orderNums.get("orderNums")==null) {
			res.setStatusInfo(StatusInfo.ERROR_40002);
			return res;
		}
		res = waimaiOrderService.deleteHistoryOrderByOrderId(orderNums.get("orderNums").toString().split(","));

		return res;
	}
	
	@RequestMapping(value = "findOtherPaySucc", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "发送代付请求成功后调用")
	public CoreResponse<Map<String,Object>> findOtherPaySucc(@RequestParam(required = true) String orderNum) {

		CoreResponse<Map<String,Object>> res = new CoreResponse<Map<String,Object>>();
		if(StringUtils.isEmpty(orderNum)){
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("参数异常！请检查参数");
			return res;
		}
		res = waimaiOrderService.findOtherPaySucc(orderNum);
		return res;
	}

	@RequestMapping(value = "getWaimaiByOrderNum",method=RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "根据订单号获取订单状态")
	public CoreResponse<WaimaiVO> getWaimaiByOrderNum(OrderQueryDto orderQueryVo) {
		CoreResponse<WaimaiVO> res = new CoreResponse<WaimaiVO>();
		if(StringUtils.isEmpty(orderQueryVo.getOrderNum())){
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("参数异常！请检查参数");
			return  res;
		}
		res = waimaiOrderService.getWaimaiByOrderNum(orderQueryVo);
		return res;
	}
	
	@RequestMapping(value = "getOrderHexiao", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取未核销订单")
	public CoreResponse<List<WaimaiVO>> getOrderHexiao(
			@RequestParam(required = true) Integer storeId, @RequestParam(required = true) String buyerId,
			@RequestParam(required = false) Integer clientOrderMode) {
		CoreResponse<List<WaimaiVO>> res = new CoreResponse<List<WaimaiVO>>();
		if (StringUtils.isEmpty(buyerId) || storeId == null) {
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("参数异常！请检查参数");
			return res;
		}
		res = waimaiOrderService.orderHexiao(storeId,buyerId,clientOrderMode);
		return res;
	}
	
	@RequestMapping(value = "updateOrderHexiao", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "订单进行核销接口（在线订单待核销订单进行核销 （店铺需要开通核销配置））")
	public CoreResponse<UpdateOrderHexiaoVO> updateOrderHexiao(@RequestBody OrderHexiaoEntryVO orderHexiaoEntry) {
		CoreResponse<UpdateOrderHexiaoVO> res = new CoreResponse<UpdateOrderHexiaoVO>();
		if (orderHexiaoEntry == null || orderHexiaoEntry.getStoreId() == null
				|| StringUtils.isEmpty(orderHexiaoEntry.getBuyerId())) {
			res.setStatusInfo(StatusInfo.ERROR_40002);
			return res;
		}
		res = waimaiOrderService.updateOrderHexiao(orderHexiaoEntry);
		return res;
	}
	
	
	@RequestMapping(value = "getSweepClose", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "承接端是否开启接单，在线订单是否在营业时间范围内")
	public CoreResponse<SweepCloseVO> getSweepClose(@RequestParam(required = true) Integer storeId, @RequestParam(required = false) Integer clientOrderMode) {
		CoreResponse<SweepCloseVO> res = new CoreResponse<SweepCloseVO>();
		if (storeId == null) {
			res.setStatusInfo(StatusInfo.ERROR_40002);
			return res;
		}
		res = waimaiOrderService.getSweepClose(storeId,clientOrderMode);
		return res;
	}
	
	
	@RequestMapping(value = "updateCupboard", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "修改取餐柜订单的柜子状态")
	public CoreResponse<Map<String,Object>> updateCupboard(HttpServletRequest request,
			@RequestBody OpenCupboardEntryVO openCupboardVO) {
		CoreResponse<Map<String,Object>> res = new CoreResponse<Map<String,Object>>();
		if (openCupboardVO == null || openCupboardVO.getStoreId() == null || openCupboardVO.getCellId() == null) {
			res.setStatusInfo(StatusInfo.ERROR_40002);
			return res;
		}
		Map<String,Object> map = waimaiOrderService.updateCupboard(openCupboardVO);
		res.setData(map);
		return res;
	}
	
	@RequestMapping(value = "onlineCupboardNum", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取在线订单待取餐的取餐柜订单数量")
	public CoreResponse<Map<String,Object>> onlineCupboardNum(HttpServletRequest request,
			@RequestParam (required=true) Integer storeId,@RequestParam(required=true) String buyerId) {
		CoreResponse<Map<String,Object>> res = new CoreResponse<Map<String,Object>>();
		if (storeId == null || StringUtils.isEmpty(buyerId)){
			res.setStatusInfo(StatusInfo.ERROR_40002);
			return res;
		}
		Map<String,Object> map = waimaiOrderService.onlineCupboardNum(storeId,buyerId);
		res.setData(map);
		return res;
	}
	
	@RequestMapping(value = "getWisdomOrderBySeq", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "根据取餐号查询智慧餐厅订单(orderSeq为四位取餐号如：0001)")
	public CoreResponse<List<WisdomOrderVO>> getWisdomOrderBySeq(HttpServletRequest request,
			@RequestParam(required = true) String orderSeq, @RequestParam(required = true) Integer storeId,
			@RequestParam(required = true) String buyerId) {
		CoreResponse<List<WisdomOrderVO>> res = new CoreResponse<List<WisdomOrderVO>>();
		if (storeId == null  || StringUtils.isEmpty(buyerId)) {
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("店铺参数有误");
			return res;
		}
		String orderSeqRe = orderSeq.replaceAll("^(0+)", "");
		if (StringUtils.isEmpty(orderSeqRe) || orderSeq.length() != 4
				|| StringUtils.isEmpty(orderSeqRe) || Integer.valueOf(orderSeqRe)<=0) {
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("取餐号参数有误");
			return res;
		}
		List<WisdomOrderVO> wisdomOrder = waimaiOrderService.getWisdomOrderBySeq(storeId, orderSeq,buyerId);
		if(CollectionUtils.isEmpty(wisdomOrder)){
			res.setData(null);
		}else{
			res.setData(wisdomOrder);
		}
		return res;
	}
	
	
	@RequestMapping(value = "getWisdomOrderInfo", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取智慧餐厅扫物料码订单信息")
	public CoreResponse<List<WisdomOrderVO>> getWisdomOrderInfo(HttpServletRequest request,
			@RequestParam (required=true) String buyerId,@RequestParam(required=true) Integer storeId) {
		CoreResponse<List<WisdomOrderVO>> res = new CoreResponse<List<WisdomOrderVO>>();
		if (storeId == null || StringUtils.isEmpty(buyerId)){
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("参数有误");
			return res;
		}
		List<WisdomOrderVO> waimaiList = waimaiOrderService.getWisdomOrderInfo(storeId,buyerId);
		res.setData(waimaiList);
		return res;
	}
	
	@RequestMapping(value = "getOrderLockInfo", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取订单是否有订单锁")
	public CoreResponse<Map<String,Object>> getOrderLockInfo(HttpServletRequest request,
			@RequestParam (required=true) String orderNum,@RequestParam(required=true) Integer storeId) {
		CoreResponse<Map<String,Object>> res = new CoreResponse<Map<String,Object>>();
		if (storeId == null || StringUtils.isEmpty(orderNum)){
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("参数有误");
			return res;
		}
		res = waimaiOrderService.getOrderLockInfo(storeId, orderNum);
		return res;
	}

	@RequestMapping(value = "getCouponList", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取会员优惠券列表")
	public CoreResponse<WaimaiVO> getCouponList(HttpSession session, HttpServletRequest request,
			@RequestParam(required = true) Integer storeId, @RequestParam(required = false) String tableName,
			@RequestParam(required = true) String buyerId, @RequestParam(required = false) String takeMealCode,
			@RequestParam(required = false) String wisdomFlag,@RequestParam(required = false) Integer clientOrderMode) {
		CoreResponse<WaimaiVO> res = new CoreResponse<WaimaiVO>();
		if (storeId == null || StringUtils.isEmpty(buyerId)) {
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("参数异常！请检查参数");
			return res;
		}
		res = waimaiOrderService.getCouponList(storeId, tableName, buyerId,takeMealCode,wisdomFlag,clientOrderMode);
		return res;
	}

	@RequestMapping(value = "getTodayNoHexiaoOrNoDeliveryOrder", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取当天未核销或者未配送的订单")
	public CoreResponse<List<WaimaiVO>> getTodayNoHexiaoOrNoDeliveryOrder(HttpSession session, HttpServletRequest request,
			@RequestParam (required=true) Integer storeId,@RequestParam(required=true) String buyerId,@RequestParam(required=true) Long outerSupportId) {
		CoreResponse<List<WaimaiVO>> res = new CoreResponse<List<WaimaiVO>>();
		if (storeId == null || StringUtils.isEmpty(buyerId) || outerSupportId == null){
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("参数有误");
			return res;
		}
		if(outerSupportId == 4){
			res = waimaiOrderService.getTodayNoHexiaoOrder(storeId, buyerId,outerSupportId);
		}else{
			res = waimaiOrderService.getTodayNoDeliveryOrder(storeId, buyerId,outerSupportId);
		}
		return res;
	}


    @RequestMapping(value = "getDistributionFee", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "计算配送费")
    public CoreResponse<Object> getDistributionFee(DistributionFeeVo distributionFeeVo){
        CoreResponse<Object> res = new CoreResponse<>();
        res.setCode(StatusInfo.FORBIDDEN.getCode());
        if(distributionFeeVo.getStoreId() == null){
            res.setSubMsg("storeId不能为空");
            return res;
        }
        if(distributionFeeVo.getUserLat() == null){
            res.setSubMsg("userLat不能为空");
            return res;
        }
        if(distributionFeeVo.getUserLng() == null){
            res.setSubMsg("userLng不能为空");
            return res;
        }
        return waimaiOrderService.getDistributionFee(distributionFeeVo);
    }

//    //查询外卖时段内
    @RequestMapping(value = "getWaimaiBusinessInfo", method = RequestMethod.GET)
    @ResponseBody
    public CoreResponse<Object> getWaimaiBusinessInfo(Integer storeId) {
        CoreResponse<Object> res = new CoreResponse<>();
        if(storeId == null){
            res.setCode(StatusInfo.FORBIDDEN.getCode());
            res.setSubMsg("storeId不能为空");
            return res;
        }
        return waimaiOrderService.getWaimaiBusinessInfo(storeId);
    }

    /*
     *<pre>
     * 说    明: 获取主账号下所有订单信息order by status,create_time 或者 appid 小程序并用
     * 涉及版本:
     * 创 建 者: YangYangjun
     * 日    期: 2020-04-10 11:25
     *</pre>
     **/
    @RequestMapping(value = "findAllOrdersByShop",method = RequestMethod.GET)
    @ResponseBody
    public CoreResponse<Object> findAllOrdersByShop(String memberUid,String appId,Long shopId, Integer pageNo, Integer pageSize, String storeName, Integer outSupportId, String buyerId) {

        CoreResponse<Object> res = new CoreResponse<>();
        try{
            pageSize = pageSize == null ? 10 :pageSize;
            pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
            return waimaiOrderService.findAllOrdersByShop(memberUid,appId,shopId,storeName,outSupportId,pageNo,pageSize,buyerId);
        }catch (Exception e){
            e.printStackTrace();
        }
        return res;
	}

}
